import tools from '@/tools'
import CryptoJS from 'crypto-js'
import {
    API_URL,
    APP_TYPE
} from '@/config/env'
import { useUserStore } from "@/store"
//判断
function isNext(isToken: boolean = false, header: any) {
    header["changjingzhi"] = uni.getStorageSync('scene') || '',
        header["platform"] = APP_TYPE
    if (isToken) {
        //用户的token
        let token = uni.getStorageSync('token') ? uni.getStorageSync('token') : ''
        if (token) {
            header["token"] = token
            return true
        } else {
            // tools.showtt('请登录后操作')
            return true
        }
    } else {
        return true
    }
}

//获取接口签名
const getInterfaceSign = function () {
    let timestamp = new Date().getTime();
    return {
        timestamp: timestamp,
        sign: CryptoJS.MD5(`${timestamp}df09e90c4144`).toString()
    };
}

//接口请求
interface optionsType<V> {
    url: string
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'HEAD' | 'OPTIONS' | 'TRACE'
    params?: V
    isToken?: boolean
}
export function aixos<T, V = any>(options: optionsType<V>): Promise<T> {
    return new Promise((resolve, reject) => {
        tools.showload('加载中')
        let header = {
            ...getInterfaceSign(),
        }
        if (isNext(options.isToken, header)) {
            uni.request({
                url: API_URL + options.url,
                method: options.method,
                header: header,
                data: {
                    ...options.params
                },
                success(res: any) {
                    uni.hideLoading();
                    if (res.data.code === 200) {
                        resolve(res.data);
                    } else if (res.data.code === 456) {
                        //重新登录
                        anewRequest<T, V>(options).then((res: any) => {
                            console.log(res.data);
                            resolve(res);
                        })
                    } else {
                        if (res.data.msg) {
                            tools.showtt(res.data.msg)
                        } else {
                            tools.showtt(`系统错误[${res.data.code}]`)
                        }
                        reject(res.data.msg);
                    }
                },
                fail(err: any) {
                    uni.hideLoading();
                    reject(err.errMsg);
                    tools.showtt('请求失败')
                },
                complete() { }
            });
        }
    });
};
//静默登录
interface silentLogin {
    url: string
    method?: 'POST'
}
export function silentLogin<T>(options: silentLogin): Promise<T> {
    return new Promise((resolve, reject) => {
        uni.login({
            success: (e) => {
                // console.log("获取登录信息：", e);
                let loginRes = {
                    code: e.code,
                    // platform: APP_TYPE
                }
                aixos<T>({
                    url: options.url,
                    method: options.method,
                    params: loginRes
                }).then((res) => {
                    resolve(res)
                }, (rej) => {
                    reject(rej)
                })
            },
            fail: (err) => {
                tools.showtt('登录调用失败')
                reject(err)
                console.log(err);
            },
            complete: () => {
                // console.log(e);
            }
        });
    });
}
//授权登录
interface authorizationLogin {
    url: string
    method?: 'POST'
}
export function authorizationLogin(options: authorizationLogin) {
    return new Promise((resolve, reject) => {
        uni.getUserInfo({
            success: function (e) {
                console.log("获取授权登录信息：", e);
                let infoRes = {
                    img: e.userInfo.avatarUrl,
                    userName: e.userInfo.nickName,
                    // platform: APP_TYPE,
                }
                aixos({
                    url: options.url,
                    method: options.method,
                    params: infoRes,
                    isToken: true
                }).then((res) => {
                    resolve(res)
                }, (rej) => {
                    reject(rej)
                })
            },
            fail: (err) => {
                tools.showtt('登录调用失败')
                reject(err)
                console.log(err);
            },
            complete: (e) => {
                console.log(e);
            }
        });
    });
}
//获取手机号
interface PhoneNumber {
    e: any
    url: string
    method?: 'POST'
}
export function getPhoneNumber(options: PhoneNumber) {
    return new Promise((resolve, reject) => {
        console.log(options.e);
        let infoRes = {
            // #ifdef MP-TOUTIAO
            encryptedData: options.e.detail.encryptedData,
            iv: options.e.detail.iv,
            // #endif
            // #ifdef MP-WEIXIN
            code: options.e.detail.code,
            // #endif
            // platform: APP_TYPE
        }
        aixos({
            url: options.url,
            method: options.method,
            params: infoRes,
            isToken: true
        }).then((res) => {
            resolve(res)
            tools.showtt('获取成功')
        }, (rej) => {
            reject(rej)
        })
    });
}
//重新获取Token并重新发起当前请求
export function anewRequest<T, V>(options: optionsType<V>) {
    return new Promise((resolve) => {
        silentLogin({ url: "third/user/login", method: "POST" }).then((res: any) => {
            const userStore = useUserStore()
            userStore.update(res.data)
            aixos<T, V>(options).then(res => {
                resolve(res)
            })
        })
    });
}
//生成支付参数并拉起支付
interface createParmas {
    url: string
    method?: 'POST'
    orderId: string | number
}
export function createParmas(options: createParmas) {
    return new Promise((resolve, reject) => {
        let parmas = {
            goodsId: options.orderId
        }
        aixos({
            url: options.url,
            method: options.method,
            params: parmas,
            isToken: true
        }).then((res: any) => {
            // resolve(res)
            payFn(res.data).then(res => {
                resolve(res)
            })
        }, rej => {
            reject(rej)
        })
    })
};


//拉起支付
export function payFn(parmas: any) {
    console.log(parmas, '支付参数')
    return new Promise((resolve, reject) => {
        uni.requestPayment({
            // #ifdef MP-WEIXIN
            ...parmas,
            // #endif
            // #ifdef MP-TOUTIAO
            orderInfo: {
                order_id: parmas.order_id,
                order_token: parmas.order_token
            },
            service: 5,
            // #endif
            success: (res) => {
                // #ifdef MP-TOUTIAO
                switch (res.code) {
                    case 0:
                        tools.showtt('支付成功', 'success')
                        resolve(res)
                        break;
                    case 1:
                        tools.showtt('支付超时', 'error')
                        break;
                    case 2:
                        tools.showtt('支付失败', 'error')
                        break;
                    case 3:
                        tools.showtt('支付关闭', 'error')
                        break;
                    case 4:
                        tools.showtt('支付取消', 'error')
                        break;
                }
                // #endif

                // #ifdef MP-WEIXIN
                tools.showtt('支付成功', 'success')
                resolve(res)
                // #endif
            },
            fail: (err) => {
                tools.showtt('支付取消', 'error')
                reject(err)
            }
        });
    })
};
//获取header
export function getHeader(isToken: boolean) {
    let header = {
        ...getInterfaceSign(),
    }
    if (isNext(isToken, header)) {
        return header
    }
}
// 上传图片
export function onUpload(url: string, count: number = 1) {
    return new Promise((resolve, reject) => {
        try {
            tools.showload('加载中')
            uni.chooseImage({
                count: count,
                sizeType: ['compressed', 'original'],
                sourceType: ['album', 'camera'],
                success: (chooseImageRes) => {
                    const tempFilePaths = chooseImageRes.tempFilePaths;
                    uni.uploadFile({
                        url: API_URL + url,
                        filePath: tempFilePaths[0],
                        name: 'file',
                        fileType: 'image',
                        header: getHeader(true),
                        success: (uploadFileRes) => {
                            let resData = JSON.parse(uploadFileRes.data);
                            resolve(resData)
                            uni.hideLoading()
                        },
                        fail() {
                            uni.hideLoading()
                            throw new Error("上传失败");
                        }
                    });
                },
                fail() {
                    uni.hideLoading()
                    throw new Error("拉起相机相册失败");
                }
            });
        } catch (err: any) {
            uni.hideLoading()
            tools.showtt(err.message)
        }
    })

}
